<?php

namespace App\Jobs;

use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Models\Chanjet\TplusSaleGrossProfitAnalysisSummary;
use App\Services\Chanjet\ChanjetExternalDataSync;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Chanjet\LogFormatRecord;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SaleGrossProfit implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $data;
    public $tries = 3;      // Laravel 自动重试次数（包括首次执行）
    public $timeout = 60;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        $data = $this->data;
        try {
            // 参数校验
            if (!isset($data["org_id"])) {
                throw new \InvalidArgumentException("缺少必要参数: org_id");
            }
            if(!isset($data["FetchDataSource"])){
                $data["FetchDataSource"] = "00";
            }
            if(!isset($data["CostPriceType"])){
                $data["CostPriceType"] = "00";
            }
            $requestParam = [
                "controllerName" => "TplusSaleGrossProfitAnalysisSummary",
                "org_id" => $data["org_id"],
                //"addRequestparam" => "",//查询条件
                "return_array" => true,
                "token" => "",
                "is_msg_notify" => false,
            ];
            $requestParam["addRequestparam"][] = ["FetchDataSource",$data["FetchDataSource"]];
            $requestParam["addRequestparam"][] = ["CostPriceType",$data["CostPriceType"]];
            $last_res = TplusSaleGrossProfitAnalysisSummary::where('is_final_profit','1')->orderBy('voucher_time', 'desc')->first();
            if($last_res){
                $requestParam["addRequestparam"][] = ["VoucherDate",$last_res["voucher_date"],date('Y-m-d')];
            }
            //销售毛利分析数据，入库时，做了特殊处理，重复数据累计
            $ChanjetExternalDataSync = new ChanjetExternalDataSync();
            $res = $ChanjetExternalDataSync->getExternalData($requestParam);
            // 处理不同 API 的响应
            $this->validateApiResponse("reportQueryGetReportData", $res);
            // 执行 API 请求
//            $api = $data["api"];
//            $param = $data["param"];
//            $res = ChanjetRequest::getInstance()->$api($param, $data["mangerinfo"]['org_id']);

            Log::info("Chanjet 销售毛利分析拉取成功", ['data' => $data]);
        } catch (\Throwable $e) {
            $this->handleFailure($e);
        }
    }

    protected function validateApiResponse(string $api, $response)
    {
        switch ($api) {
            case "reportQueryGetReportData": //
                if ($response['code'] != '000') {
                    throw new \RuntimeException("Chanjet {$api} 请求失败");
                }
                break;
        }
    }

    protected function handleFailure(\Throwable $e)
    {
        // 参数错误立即失败，不重试
        if ($e instanceof \InvalidArgumentException) {
            $this->failed($e);
            return;
        }

        // 可重试错误：达到最大尝试次数后标记失败
        if ($e instanceof \RuntimeException) {
            if ($this->attempts() >= $this->tries) {
                $this->failed($e);
            }else{
                throw $e;
            }
        }
    }

    public function failed(\Throwable $exception)
    {
        // 静默记录日志（非 error 级别）
        Log::info($exception->getMessage().'failed方法');
//        $this->data["error"] = $exception->getMessage();
//        $this->data["res"] = "Chanjet 调拨单任务,同步失败";
        //LogFormatRecord::error($this->data);
        return;
    }
}
